﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using ZhukBlogLinqExamples.Repositories;

namespace ZhukBlogLinqExamples.FieldTypes.CustomUser.Controls
{
    public class CustomUserFieldPicker : PeopleEditor
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            PickerDialogType = typeof(CustomUserFieldPickerDialog);
        }

public override PickerEntity ValidateEntity(PickerEntity entity)
{
    if (entity == null) return null;
    if (entity.IsResolved) return entity;
    var repository = new EmployeeRepository(true);
    var filter = entity.DisplayText;
    var emps = repository.GetEntityCollection(
        x => x.Title.Contains(filter) || x.CellPhone.Contains(filter))
        .Take(2)
        .ToList();
    if (emps.Count == 1)
    {
        entity = emps[0].ToPickerEntity();
    }
    else
    {
        entity.IsResolved = false;
    }
    return entity;
}

protected override PickerEntity[] ResolveErrorBySearch(string unresolvedText)
{
    var repository = new EmployeeRepository(true);
    var emps = repository.GetEntityCollection(
        x => x.Title.Contains(unresolvedText) || x.CellPhone.Contains(unresolvedText))
        .Take(1)
        .ToList();
    return emps.Select(x => x.ToPickerEntity()).ToArray();
}

        public override string DialogTitle
        {
            get
            {
                return "Поиск сотрудников";
            }
            set
            {
                base.DialogTitle = value;
            }
        }
    }
}
